/*
 * @Date: 2023-10-19 14:23:34
 * @LastEditors: lyx
 * @LastEditTime: 2023-11-15 19:40:20
 * @FilePath: \sup-mini-app\src\pages\login\hooks\useLogin.tsx
 * @Description:
 */
import { getOpenId, getPhoneNumber, getOpenIdByWx } from "@/services/login";
// import WXBizDataCrypt from "@/utils/WXBizDataCrypt";
import Taro from "@tarojs/taro";
import React, { useState } from "react";

function useLogin() {
  const [fail, failState] = useState(false);
  const [failText, failTextState] = useState("错误提示");
  const [dialogType, dialogTypeState] = useState<
    "error" | "loading" | "success"
  >("error");
  const [phone, phoneState] = useState("");
  const [userInfo, userInfoState] = useState({});
  const [inputPhone, setInputPhone] = useState("");

  const [modalOpen, setModalOpen] = useState(false);
  // 从 obp 获取的用户
  const [obpUser, setObpUser] = useState<IUserInfo>({} as any);
  const style = {
    width: "100%",
    height: "100%",
  };
  const getUserProfile = () => {
    Taro.getUserProfile({
      desc: "用户登录", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(" getUserProfile res ", res);
        userInfoState(res.userInfo);
      },
    });
  };
  const getPhonenNmber = (e) => {
    console.log(" getPhonenNmber e ", e);
    const iv = e.detail.iv;
    const encryptedData = e.detail.encryptedData;
    // 登录
    Taro.login({
      success: async (res) => {
        console.log("login res", res);
        if (res.code) {
        } else {
          errorDialog("登录失败！" + res.errMsg, "error");
        }
      },
    });
  };
  const errorDialog = (text, type) => {
    failState(true);
    failTextState(text);
    dialogTypeState(type);
    setTimeout(() => {
      failState(false);
    }, 1000);
  };

  const getObpUserList = () => {
    Taro.showLoading({
      title: "加载中",
    });
    setTimeout(() => {
      setObpUser({
        id: 29251,
        username: "liyixin",
        code: "liyixin",
        nickName: "撕葱",
        gender: 1,
        phone: "13616859570",
        email: "13616859570@163.com",
        status: 0,
        type: 1,
        icon: "",
        loginTime: "2023-11-14 16:46:16",
      });
      Taro.hideLoading();
      setModalOpen(true);
    }, 3000);
  };

  /**
   * @description: 绑定用户
   * @return {*}
   */
  const bindObpUser = () => {
    // 调用 login 获取 code 凭证
    Taro.login({
      success: async (res) => {
        if (res.code) {
          // 获取用户唯一id
          const { status, msg } = await getOpenIdByWx(res.code, obpUser.phone);

          if (status) {
            // 保存
            Taro.setStorage({
              key: "phoneNumber",
              data: obpUser.phone,
            });

            // 储存用户唯一openid到后端
            errorDialog("绑定成功", "success");
          } else {
            errorDialog("openId获取失败！" + msg, "error");
          }
        } else {
          errorDialog("登录失败！" + res.errMsg, "error");
        }
        setModalOpen(false);
      },
    });
  };

  return {
    fail,
    dialogType,
    failText,
    userInfo,
    phone,
    style,
    inputPhone,
    modalOpen,
    obpUser,
    getPhonenNmber,
    getUserProfile,
    setInputPhone,
    getObpUserList,
    setModalOpen,
    bindObpUser,
  };
}

export default useLogin;
